// 商品列表
<template>
  <div class="product-list">
    <h2>商品列表</h2>

    <!-- 搜索和过滤 -->
    <div class="d-flex mb-4">
      <input
          type="text"
          class="form-control me-2"
          placeholder="搜索商品..."
          v-model="searchTerm"
      >
      <button class="btn btn-outline-primary" @click="loadProducts">
        <i class="bi bi-search"></i> 搜索
      </button>
    </div>

    <!-- 商品展示 -->
    <div class="row">
      <div
          v-for="product in products"
          :key="product.id"
          class="col-md-4 mb-4"
      >
        <div class="card h-100">
          <img
              :src="product.imageUrl || 'https://via.placeholder.com/150'"
              class="card-img-top"
              alt="商品图片"
          >
          <div class="card-body">
            <h5 class="card-title">{{ product.name }}</h5>
            <p class="card-text">{{ product.description }}</p>
            <p class="text-danger fw-bold">¥{{ product.price }}</p>
          </div>
          <div class="card-footer">
            <button
                class="btn btn-primary"
                @click="addToCart(product)"
                :disabled="!isBuyer"
            >
              <i class="bi bi-cart-plus"></i> 加入购物车
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 管理员/卖家操作按钮 -->
    <div v-if="isAdmin || isSeller" class="mt-4">
      <router-link to="/admin/products" class="btn btn-success">
        <i class="bi bi-plus-circle"></i> 添加新商品
      </router-link>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { productApi, cartApi } from '@/api'

export default {
  setup() {
    const products = ref([])
    const searchTerm = ref('')
    const userId = localStorage.getItem('userId')
    const userRole = localStorage.getItem('role')

    const isBuyer = computed(() => userRole === 'BUYER')
    const isSeller = computed(() => userRole === 'SELLER')
    const isAdmin = computed(() => userRole === 'ADMIN')

    const loadProducts = async () => {
      try {
        products.value = await productApi.getAll()
      } catch (error) {
        console.error('加载商品失败:', error)
      }
    }

    const addToCart = async (product) => {
      if (!userId) {
        alert('请先登录')
        return
      }

      try {
        await cartApi.addItem({
          productId: product.id,
          quantity: 1,
          userId
        })
        alert('已添加到购物车')
      } catch (error) {
        console.error('添加到购物车失败:', error)
      }
    }

    onMounted(loadProducts)

    return {
      products,
      searchTerm,
      isBuyer,
      isSeller,
      isAdmin,
      loadProducts,
      addToCart
    }
  }
}
</script>

<style scoped>
.card {
  transition: transform 0.2s;
}
.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
</style>